import time
import logging
import os
import re
from urllib.parse import urlparse, parse_qs
from selenium import webdriver

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException
from selenium.webdriver.remote.webelement import WebElement
from selenium.common.exceptions import StaleElementReferenceException
# 设置日志
logging.basicConfig(filename='my.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger('example_logger')


# 获取课程列表
def getCourseList():
    try:
        # # 等待<a>元素加载完成
        # elements = WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.XPATH, "//td[@class='text-center sub_col font-size-sm']/nobr/a[text()='学习']")))
        # for element in elements:
        #     print(element)
        course_list = []
        not_need = ['BKS004','BKS005']
        tbody = driver.find_element(By.XPATH, "//table/tbody")
        # 获取表格中的所有行
        rows = tbody.find_elements(By.TAG_NAME, "tr")
        # 遍历每一行，并获取每一行中的单元格数据
        for row in rows:
            # 获取当前行中的所有单元格
            cells = row.find_elements(By.TAG_NAME, "td")
            # 遍历每一个单元格，并打印其文本内容
            for cell in cells:
                if("学习" == cell.text and cells[0].text not in not_need):
                    # url1 = "https://stu.5zk.com.cn/zk8exam/jp_wiki_study.php?kcdm="
                    # url2 = "https://stu.5zk.com.cn/zk8exam/live.php?kcdm="
                    # base_url = "https://stu.5zk.com.cn/zk8exam/"
                    link_element = cell.find_element(By.XPATH, ".//a[contains(text(), '学习')]")
                    # 获取链接的href属性值
                    href_value = link_element.get_attribute("href")
                    url = href_value if href_value else ""
                    person = {"path":url, "button": cell,"score": cells[7].text}
                    course_list.append(person)
                    print(person)
                    logger.info("课程编码：",cells[0].text,"课程名称：",cells[1].text,"学习分值：",cells[7].text,"学习进度：",cells[9].text,"课程地址："+url)

        return course_list
    except Exception as e:
         print(e)


# 点击跳转学习
def goToStartTableStudy(course_list,start_index):
    try:
        # driver.get("https://stu.5zk.com.cn/zk8exam/mycourse.php")
        # # 等待<a>元素加载完成
        # elements = WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.XPATH, "//td[@class='text-center sub_col font-size-sm']/nobr/a[text()='学习']")))
        # for element in elements:
        #     print(element)
        # 如果元素出现，则进行点击操作
        # print(course_list[start_index])
        # course_list[start_index].button.click()
        # 获取当前窗口句柄
        button_element = course_list[start_index]['button']
        if isinstance(button_element, WebElement):
           button_element.click()
           # 等待新页面加载完成
        WebDriverWait(driver, 10).until(EC.url_changes(driver.current_url))

        # 获取新页面的 URL
        new_url = driver.current_url
        return course_list[start_index]['path'] if course_list[start_index]['path'] !='javascript:void(0);' else new_url
    except Exception as e:
        print("点击学习跳转错误：",str(e))
#获取章节列表
def getChapterList(driver,url):
     try:
        print("章节地址",driver.current_url)
        driver.get(url)
        driver.refresh()
        time.sleep(2)
        #driver.get("https://stu.5zk.com.cn/zk8exam/jp_wiki_study.php?kcdm=BKS004")
        # 点击所有课程选项
        video_links = []
        is_rcord = False
        try:
            button = WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable((By.CSS_SELECTOR, "button.btn-block-option[data-action='side_overlay_toggle']"))
            )
            is_rcord = True
            button.click()
        except (TimeoutException, NoSuchElementException):
            print("不是录播")

        print("是否是录播：",is_rcord)
        # 判断是否是录播
        if is_rcord:
           
            # 等待弹窗出现，并获取其中的元素
            # 找到弹窗中的所有匹配元素,红色 和 橙色
            # elements = popup_wrapper.find_elements(By.XPATH, "//li[.//span[contains(@style, 'color:#EA0000;')] or .//span[contains(@style, 'color:#FF8000;')]]")
            try:
                popup_wrapper = WebDriverWait(driver, 10).until(
                    EC.presence_of_element_located((By.XPATH, "//div[@class='simplebar-wrapper']"))
                )
                # elements = WebDriverWait(popup_wrapper, 10).until(
                #     EC.presence_of_all_elements_located((By.CSS_SELECTOR, "li span[style*='color:#EA0000;'], li span[style*='color:#FF8000;']"))
                # )
                # print("录播视频链接：",elements)
                elements = popup_wrapper.find_elements(By.XPATH, "//li[.//span[contains(@style, 'color:#EA0000;')] or .//span[contains(@style, 'color:#FF8000;')]]")
                #if elements:
                for element in elements:

                    link_element = element.find_element(By.TAG_NAME, 'a')
                    # 获取链接属性 href
                    href = link_element.get_attribute('href')
                    print(href)  # 或者做其他处理
                    print("录播视频链接：",href)
                    if href == None:
                        continue
                    video_links.append(href)
                # 在找到元素后，执行接下来的操作
            except (TimeoutException, NoSuchElementException) as e:
                #driver.refresh()
                print("无法获取录播视频链接:", e)
        else:
            replay_links = []
            try:
                table = WebDriverWait(driver, 10).until(
                    EC.presence_of_element_located((By.TAG_NAME, "table"))
                )
                replay_links = table.find_elements(By.XPATH, "//td[contains(@class, 'text-center') and contains(@class, 'sub_col') and contains(@class, 'font-size-sm')]//a[contains(@href, 'zb_wiki_study.php')]")
            except (TimeoutException, NoSuchElementException) as e:
                print("无法获取回放视频链接:", e)
            # 打印所有链接的 href 属性值
            for link in replay_links:
                if link.get_attribute("href") == None:
                    continue  
                video_links.append(link.get_attribute("href"))
        return video_links,is_rcord       
     except Exception as e:
        print("发生异常:", e)
     return [], False
#获取视频链接
def elementToVideoLink(element):
    try:
        link = WebDriverWait(element, 10).until(
            EC.presence_of_element_located((By.TAG_NAME, 'a'))
        )
        if link:
            # 如果链接元素成功找到，返回链接的属性值
            return link.get_attribute('href')
        else:
            print("未找到链接元素")
            return None
    except NoSuchElementException:
        print("未找到链接元素")
        return None

# 自定义异常类
class PlayButtonNotFoundException(Exception):
    """自定义异常类，用于指示未找到播放按钮的情况。"""
    pass
#打开录播视频
def openVideo(video_link):

    # 打开视频链接
    driver.get(video_link)
    # 切换到新窗口
    driver.switch_to.window(driver.window_handles[-1])
    driver.refresh()
    try:
        player_container = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.ID, "player-container-id"))
        )
        # 定义播放按钮的 CSS 选择器列表
        play_button_selectors = [".bigplaybtn", ".vjs-big-play-button"]

        # 尝试查找并点击播放按钮
        for selector in play_button_selectors:
            try:
                # 在播放器容器内等待播放按钮可点击
                play_button = WebDriverWait(player_container, 10).until(
                    EC.element_to_be_clickable((By.CSS_SELECTOR, selector))
                )
                play_button.click()
                break  # 找到并点击播放按钮后跳出循环
            except (TimeoutException,NoSuchElementException):
                # 如果超时，继续尝试下一个选择器
                pass 
        # 获取视频播放器
        # video_player = player_container.find_element(By.TAG_NAME, "video")
        video_player = WebDriverWait(player_container, 10).until(
            EC.presence_of_element_located((By.TAG_NAME, "video"))
        )

        #video_player.play()
        while True:
            # 检查视频是否已经播放完毕
            # is_ended = driver.execute_script("return arguments[0].ended", video_player)
            is_ended = video_player.get_attribute("ended")
            print("是否结束：",is_ended)
            if is_ended:
                # 如果视频播放完毕，退出循环
                break
            # 检查视频是否处于播放状态
            # is_playing = driver.execute_script("return arguments[0].paused === false", video_player)
            is_playing = not video_player.get_attribute("paused")
            print("是否播放：",is_playing)
            # 如果视频未处于播放状态，则点击播放按钮
            if not is_playing and not is_ended:
                # 点击播放按钮
                #driver.execute_script("arguments[0].play()", video_player)
                # video_player.play()
                # 播放视频
                video_player.play()

            # 检查是否有 alert 弹窗出现
            try:
                # 等待弹出层(alert)出现
                alert = WebDriverWait(driver, 3).until(EC.alert_is_present())
                # 在弹出层上执行操作
                # 例如点击确认按钮
                alert.accept()
                time.sleep(2)
                break
            except StaleElementReferenceException:
                # 如果出现"stale element reference"错误，重新尝试操作
                print("出现stale element reference错误，重新尝试操作")
                # 重新等待弹出层(alert)出现
                alert = WebDriverWait(driver, 3).until(EC.alert_is_present())
                # 在弹出层上执行操作
                # 例如点击确认按钮
                alert.accept()
                break

            except Exception as e:
                pass
            # 等待一段时间后再次检查
            time.sleep(1)
            print("-------")
    except Exception as e:
        print("打开视频链接错误：",str(e))



# 用户数据目录，将其替换为你自己的Chrome用户数据目录路径
#user_data_dir = 'C:/Users/Administrator/AppData/Local/Google/Chrome/User'
# 获取当前用户的 AppData 文件夹路径
appdata_path = os.environ['LOCALAPPDATA']
# 构建谷歌 Chrome 用户数据文件夹的完整路径
user_data_dir = os.path.join(appdata_path, 'Google', 'Chrome', 'User')

print(user_data_dir)
# 创建 Chrome 选项
chrome_options = webdriver.ChromeOptions()

# 设置用户数据目录
chrome_options.add_argument("--user-data-dir=" + user_data_dir)

# 设置用户代理
user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117"
chrome_options.add_argument('--user-agent=%s' % user_agent)

# 禁用弹出窗口阻止
chrome_options.add_argument("--disable-popup-blocking")

# 创建Chrome实例
driver = webdriver.Chrome(options=chrome_options)
# 打开网页，跳转到登录地址
driver.get("https://stu.5zk.com.cn/zk8exam/login.php")
driver.implicitly_wait(10)
driver.maximize_window()
# 登录
username_input = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.NAME, "admin_name"))  # 将 "username" 替换为实际用户名输入框的 name 属性值
)
password_input = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.NAME, "admin_password"))  # 将 "password" 替换为实际密码输入框的 name 属性值
)
# 输入用户名和密码
username_input.send_keys("xxxxx")
password_input.send_keys("xxxxx")
time.sleep(2)

# 找到单选框元素并点击选择
# 找到并点击 type 为 "submit" 的按钮
submit_button = driver.find_element(By.CSS_SELECTOR, 'button[type="submit"]')
submit_button.click()

# 设置等待时间为10秒
try:

    base_url = 'https://stu.5zk.com.cn/zk8exam/'
    course_match = {
        'gotoxx':'jp_wiki_study.php?kcdm=',
        'gotolx':'studycenter_zy.php?kcdm=',
        'gotocp':'studycenter_cy.php?kcdm=',
    }
    elements = WebDriverWait(driver, 10).until(
        EC.presence_of_all_elements_located((By.XPATH, "//td[@class='text-center sub_col font-size-sm']/nobr/a"))
    )
    for element in elements:
        onclick_value = element.get_attribute("onclick")
        #print(onclick_value)
        if onclick_value:
            match = re.search(r'(\w+)\((.*?)\)', onclick_value)
            if match:
                function_name = match.group(1)
                parameters    = match.group(2).split(',')
                # 剔除播放的课程
                if parameters[1].replace("'", "")  in ['BKS004','BKS005']:
                    continue
                
                url = ''.join([base_url,course_match[function_name],parameters[1].replace("'", "")])
                print(f"课程编码：{parameters[1]},函数名：{function_name},课程地址：{url}")
                video_links,is_rcord    = getChapterList(driver,url)
                if len(video_links) == 0 or video_links == None:
                    print("该课程没有视频")
                    logger.info(f"该课程没有视频{parameters[1]},课程地址：{url}")
                    continue
                # # 获取视频地址
                for i, video_link in enumerate(video_links):
                    print(f"正在播放第 {i+1} 个视频：{video_link}")
                    if video_link != '':
                        # 解析URL
                        logger.info(f"正在播放视频地址：{video_link},是否是录播：{is_rcord}")
                        openVideo(video_link)

    print("结束")
except Exception as e:
    # continue
    print("error",str(e))

try:
    # 进入无限循环等待用户关闭浏览器
    while True:
        time.sleep(1)  # 每隔1秒检查一次
except KeyboardInterrupt:
    # 用户按下Ctrl+C退出循环时执行关闭浏览器的操作
    driver.quit()
